//配置路由的地方
import Vue from 'vue';
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
const originPush = VueRouter.prototype.push;
const originReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function push(location, resolve, reject) {
    if (resolve || reject) return originPush.call(this, location, resolve, reject)
    return originPush.call(this, location).catch(err => err)
};
VueRouter.prototype.replace = function push(location, resolve, reject) {
    if (resolve || reject) return originReplace.call(this, location, resolve, reject)
    return originReplace.call(this, location).catch(err => err)
};

//使用插件
Vue.use(VueRouter)

//配置路由
let router = new VueRouter({
    routes,
    // mode: 'history',
    scrollBehavior(to, from, savedPosition) {
        //返回的y:0,代表跳转的时候滚动条在距离顶部0
        return { y: 0 }
    }
})

// 全局守卫(前置守卫)
router.beforeEach(async (to, from, next) => {
    next()
    //如果用户登录了一定有token,没有登录肯定没有token
    let token = store.state.user.token
    let name = store.state.user.userInfo.name
    // console.log(token, '--', name);
    if (token) {
        //用户已经登录,想去登录页面
        if (to.path == '/login') {
            next('/')
        } else {
            //用户已经登录,去的不是登录页面
            if (name) {
                next()
            } else {
                //没有用户信息,让仓库派发action再跳转
                try {
                    //获取用户信息成功
                    await store.dispatch("getUserInfo");
                    next()
                } catch (error) {
                    //token失效了,获取不到用户信息,需要重新登陆
                    await store.dispatch('userLogout')
                    next('/login')
                }
            }
        }
    } else {
        //未登录  不能去交易相关的页面    都应该跳登陆页面
        let toPath = to.path
        if (toPath.indexOf('/trade') != -1 || toPath.indexOf('/pay') != -1 || toPath.indexOf('/center') != -1) {
            //把未登录时候想去而没有去成的路由信息存储在地址栏中(也就是路由中)
            next('/login?redirect=' + toPath)
        } else {
            next()
        }
    }
})

export default router